package com.itheima.web.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.Question;
import com.itheima.domain.Result;
import com.itheima.factory.BeanFactory;
import com.itheima.service.QuestionService;
import com.itheima.utils.BeanUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;


@WebServlet("/store/question/*")
public class QuestionServlet extends BaseServlet {
    //    @Override
//    protected Result doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, Exception {
//        //1 获取请求标记
//        //获取Servlet一级目录后面的路径 ，也就是/list、/save、/edit、/delete 等
//        String info = req.getPathInfo().substring(1);
//        //2 判断标记，调用不同的方法处理请求
//        if ("findByPage".equals(info)){
//            findByPage(req,resp);
//        }else if ("save".equals(info)){
//            save(req,resp);
//        }else if ("findById".equals(info)){
//            findById(req,resp);
//        }else if ("edit".equals(info)){
//            edit(req,resp);
//        }else if ("delete".equals(info)){
//            delete(req,resp);
//        }
//    }
    private QuestionService questionService = BeanFactory.getService("questionService", QuestionService.class);

    private Result toExport(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 设置content-disposition响应头，告诉浏览器以附件(文件下载)的方式弹框
            resp.setHeader("content-disposition","attachment;filename=question.xlsx");
            //2 调用service层方法，生成xlsx表格，进行输出
            questionService.toExport(resp.getOutputStream());
            //响应结果
            return new Result(true,MessageConstant. QUESTION_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUESTION_EXPORT_FAIL);
        }

    }

    private Result upload(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //【第一步】判断是否请求是否支持文件上传
//            if (ServletFileUpload.isMultipartContent(req)) {
                //【第二步】创建磁盘工厂对象，用于将页面上传的文件保存到硬盘中。
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //【第三步】创建ServletFileUpload文件上传核心对象
                ServletFileUpload fileUpload = new ServletFileUpload(factory);
                //【第四步】解析请求对象，获取表单项集合
                List<FileItem> fileItems = fileUpload.parseRequest(req);
                //【第五步】遍历集合，判断是普通表单项还是文件上传项，如果是文件上传项就将文件写到服务器硬盘中。
                //但是我的项目一次只能上传一张图片所以不用遍历可以直接拿到一张
                FileItem fileItem = fileItems.get(0);
                //获取文件保存的位置
                String realPath = getServletContext().getRealPath("/upload");
                //原始文件名
                String name = fileItem.getName();
                //需求：生成唯一不重复的文件名
                String uuid = UUID.randomUUID().toString().replace("-", "");
                //获取后缀名
                String fname = name.substring(name.lastIndexOf("."));
                //组合新的文件名
                //写到硬盘中
                String fileName = uuid+fname;
                fileItem.write(new File(realPath, fileName));
//            }
            return new Result(true, MessageConstant.UPLOAD_QUESTIONIMG_SUCCESS,fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.UPLOAD_QUESTIONIMG_FAIL);
        }
    }





    private Result findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //2 调用service层方法获取分页结果
            List<Question> list= questionService.findAll();
            //3 对客户的作出响应
            return new Result(true,MessageConstant.QUERY_QUESTION_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
        }
    }

    private Result delete(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数并封装成Question对象
            String[] ids = BeanUtil.fillBeanFromJson(req, String[].class);
            //2 调用service层方法添加数据
            questionService.delete(ids);
            //3 响应结果
            return new Result(true,MessageConstant.DELETE_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_QUESTION_FAIL);
        }
    }

    private Result edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数并封装成Question对象
            Question question = BeanUtil.fillBeanFromJson(req, Question.class);
            //2 调用service层方法添加数据
            questionService.update(question);
            //3 响应结果
            return new Result(true,MessageConstant.EDIT_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_QUESTION_FAIL);
        }
    }

    private Result findById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数
            String id = req.getParameter("id");
            //2 调用service层方法获取分页结果
            Question question = questionService.findById(id);
            //3 对客户的作出响应
            return new Result(true,MessageConstant.QUERY_QUESTION_SUCCESS,question);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
        }
    }

    private Result save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数并封装成Question对象
            Question question = BeanUtil.fillBeanFromJson(req, Question.class);
            //2 调用service层方法添加数据
            questionService.save(question);
            //3 响应结果
            return new Result(true,MessageConstant.SAVE_QUESTION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SAVE_QUESTION_FAIL);
        }
    }

    /*
     * 处理分页查询的请求
     * @param request
     * @param response
     */
    private Result findByPage(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            //1 获取请求参数（当前页数和每页条数）
            String currentPage1 = req.getParameter("currentPage");
            String pageSize1 = req.getParameter("pageSize");
            //2.判断是否为空
            int currentPage = 1,pageSize = 5;
            if (!StringUtils.isBlank(currentPage1)){
                //3.给页码和条数赋默认值
                currentPage = Integer.parseInt(currentPage1);

            }
            if (!StringUtils.isBlank(pageSize1)){
                //3.给页码和条数赋默认值
                pageSize = Integer.parseInt(pageSize1);

            }
//            QuestionServlet questionServlet = new QuestionServiceImpl();
            //4.调用Service层方法获得结果
            PageInfo<Question> page = questionService.findByPage(currentPage, pageSize);
            //5.给客户端响应
            return new Result(true,MessageConstant.QUERY_QUESTION_SUCCESS,page);
        } catch (Exception e) {
            e.printStackTrace();
           return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
        }
    }

//    @Override
//    protected Result doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, Exception {
//        doGet(req, resp);
//    }
}
